/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.eit.eitsite.common.utils.DateUtils;
import com.eit.eitsite.common.utils.IdGen;
import com.eit.eitsite.common.utils.SpringContextHolder;
import com.eit.eitsite.modules.sys.entity.Dict;
import com.eit.eitsite.modules.sys.service.DictService;
import com.eit.eitsite.modules.sys.utils.DictUtils;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.zhuoyue.elmt.UserFilterUtils;
import com.zhuoyue.elmt.dao.FailureReportDao;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.*;
import com.zhuoyue.elmt.service.*;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 电梯维保记录Controller
 *
 * @author chenhao
 * @version 2016-09-07
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/maintenanceRecordSz")
public class MaintenanceRecordSzController extends BaseController {

    @Autowired
    private MaintenanceRecordSzService maintenanceRecordSzService;

    @Autowired
    private MaintenanceStaffService maintenanceStaffService;

    @Autowired
    private DeviceParametersService deviceParametersService;

    @Autowired
    private DictService dictService;

    @Autowired
    private MtItemService mtItemService;

    @Autowired
    private AdministrativeAreasService service;

    @Autowired
    private XtSbzlService xtSbzlService;

    @ModelAttribute
    public MaintenanceRecordSz get(@RequestParam(required = false) String recordId) {
        MaintenanceRecordSz entity = null;
        if (StringUtils.isNotBlank(recordId)) {
            entity = maintenanceRecordSzService.get(recordId);
        }
        if (entity == null) {
            entity = new MaintenanceRecordSz();
        }
        return entity;
    }

    /**
     * 根据设备代码查询当前处理的维保记录
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getMaintenanceRecordByDeviceCode/{str1}")
    public String getMaintenanceRecordByDeviceCode(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("根据设备代码查询当前处理的维保记录 ===========================================>>>>>>>>>>>>>>");
            HashMap params = new HashMap();
            params.put("deviceCode", str1);
            params.put("createdBy", UserUtils.getUser().getLoginName());
            MaintenanceRecordSz record = maintenanceRecordSzService.getMaintenanceRecordByDeviceCode(params);
            if (record != null) {
                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的电梯维保记录！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯维保记录查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询单条维保记录
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getMaintenanceRecordInfo/{str1}")
    public String getMaintenanceRecordInfo(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("查询单条维保记录 ===========================================>>>>>>>>>>>>>>");
            MaintenanceRecordSz record = maintenanceRecordSzService.get(str1);
            if (record != null) {
                // 拿到设备对应的维保人员列表
                MaintenanceStaff qryMaintenanceStaff = new MaintenanceStaff();
                qryMaintenanceStaff.setWbdwdm(UserUtils.getUser().getCompany().getCode());
                qryMaintenanceStaff.setDeviceCode(record.getDeviceCode());

                List<MaintenanceStaff> staffList = maintenanceStaffService.findDeviceMainStaffList(qryMaintenanceStaff);
                record.setStaffList(staffList);

                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的电梯维保记录！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯维保记录查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询多条维保记录
     *
     * @param maintenanceRecordSz
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/findMaintenanceRecordInfo")
    public String findMaintenanceRecordInfo(MaintenanceRecordSz maintenanceRecordSz, String mainType, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        try {
            System.out.println("查询多条维保记录 ===========================================>>>>>>>>>>>>>>");

            // 设置维保人员和维保单位代码过滤条件
            // maintenanceRecordSz.setCreatedBy(UserFilterUtils.getMainStaff());
            maintenanceRecordSz.setDbName(Global.getConfig("jdbc.type"));
            maintenanceRecordSz.setMaintenUnitCode(UserFilterUtils.getMainUnitCode());
            if ("halfmonth".equals(mainType)) {
                maintenanceRecordSz.setHalfmonthMainType("1");
            }
            if ("quarter".equals(mainType)) {
                maintenanceRecordSz.setQuarterMainType("1");
            }
            if ("halfyear".equals(mainType)) {
                maintenanceRecordSz.setHalfyearMainType("1");
            }
            if ("year".equals(mainType)) {
                maintenanceRecordSz.setYearMainType("1");
            }

            Page<MaintenanceRecordSz> page = maintenanceRecordSzService.findPage(new Page<MaintenanceRecordSz>(request, response), maintenanceRecordSz);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯维保记录查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/validMainNum")
    public String validMainNum(MaintenanceRecordSz maintenanceRecordSz, Model model, HttpServletRequest request, HttpServletResponse response) {
        ResultData resultData = new ResultData();
        try {
            // 拿到设备对应的合同号
            String contractId = deviceParametersService.getDeviceEffContractId(maintenanceRecordSz.getDeviceCode());
            maintenanceRecordSz.setContractId(contractId);

            // 判断数据库中是否已有相同的维保类型次数
            List<MaintenanceRecordSz> mainContractList = maintenanceRecordSzService.findMainContractMtNum(maintenanceRecordSz);
            if (mainContractList != null && mainContractList.size() > 0) {
                String count1 = "";
                String count2 = "";
                String count3 = "";
                String count4 = "";
                for (MaintenanceRecordSz retMaintenanceRecordSz : mainContractList) {
                    if ("1".equals(retMaintenanceRecordSz.getCount1())) {
                        if (StringUtils.isEmpty(count1)) {
                            count1 = "例行维保,";
                        }
                    }
                    if ("2".equals(retMaintenanceRecordSz.getCount2())) {
                        if (StringUtils.isEmpty(count2)) {
                            count1 = "季度维保,";
                        }
                    }
                    if ("3".equals(retMaintenanceRecordSz.getCount3())) {
                        if (StringUtils.isEmpty(count3)) {
                            count1 = "半年维保,";
                        }
                    }
                    if ("4".equals(retMaintenanceRecordSz.getCount4())) {
                        if (StringUtils.isEmpty(count4)) {
                            count1 = "年度维保";
                        }
                    }
                }

                resultData.setCode("FAIL");
                resultData.setMessage(count1 + count2 + count3 + count4 + "的次数已存在");
            } else {
                resultData.setCode("SUCC");
                resultData.setMessage("维保类型次数可增加");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("维保类型出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/saveMaintenanceRecordInfo")
    public String saveMaintenanceRecordInfo(MaintenanceRecordSz maintenanceRecordSz, Model model, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("增加电梯维保记录 ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, maintenanceRecordSz)) {
                return form(maintenanceRecordSz, model);
            }

            uploadMtFile(maintenanceRecordSz, request, resultData);
            maintenanceRecordSz.setMaintenanceStaff(UserUtils.getUser().getLoginName());

            if (maintenanceRecordSz.getRecordId() == null) {
                maintenanceRecordSz.setCreatedBy(UserUtils.getUser().getLoginName()); // 创建者
            }

            // 拿到设备对应的合同号
            String contractId = deviceParametersService.getDeviceEffContractId(maintenanceRecordSz.getDeviceCode());
            maintenanceRecordSz.setContractId(contractId);

            // 判断数据库中是否已有相同的维保类型次数
            List<MaintenanceRecordSz> mainContractList = maintenanceRecordSzService.findMainContractMtNum(maintenanceRecordSz);
            if (mainContractList != null && mainContractList.size() > 0) {
                String count1 = "";
                String count2 = "";
                String count3 = "";
                String count4 = "";
                for (MaintenanceRecordSz retMaintenanceRecordSz : mainContractList) {
                    if ("1".equals(retMaintenanceRecordSz.getCount1())) {
                        if (StringUtils.isEmpty(count1)) {
                            count1 = "例行维保,";
                        }
                    }
                    if ("2".equals(retMaintenanceRecordSz.getCount2())) {
                        if (StringUtils.isEmpty(count2)) {
                            count1 = "季度维保,";
                        }
                    }
                    if ("3".equals(retMaintenanceRecordSz.getCount3())) {
                        if (StringUtils.isEmpty(count3)) {
                            count1 = "半年维保,";
                        }
                    }
                    if ("4".equals(retMaintenanceRecordSz.getCount4())) {
                        if (StringUtils.isEmpty(count4)) {
                            count1 = "年度维保";
                        }
                    }
                }

                resultData.setCode("FAIL");
                resultData.setMessage(count1 + count2 + count3 + count4 + "的次数已存在");
            } else {

                maintenanceRecordSz.setLastUpdateBy(UserUtils.getUser().getLoginName());

                maintenanceRecordSzService.save(maintenanceRecordSz);
                System.out.println("wbMaintenanceRecordSz.getRecordId() ================>>>>>>>>>>>>>> " + maintenanceRecordSz.getRecordId());

                //增加返回model
                list.add(maintenanceRecordSz);
                resultData.setList(list);

                resultData.setFormId(maintenanceRecordSz.getRecordId());
                resultData.setCode("SUCC");
                resultData.setMessage("增加电梯维保记录成功");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("增加电梯维保记录出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updateMaintenanceRecordByBaseInfo")
    public String updateMaintenanceRecordByBaseInfo(MaintenanceRecordSz maintenanceRecordSz, Model model, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("更新电梯维保记录（基本情况） ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, maintenanceRecordSz)) {
                return form(maintenanceRecordSz, model);
            }
            if (StringUtils.isNotEmpty(maintenanceRecordSz.getRecordId())) {

                uploadMtFile(maintenanceRecordSz, request, resultData);

                maintenanceRecordSz.setLastUpdateBy(UserUtils.getUser().getLoginName());
                maintenanceRecordSzService.updateMaintenanceRecordByBaseInfo(maintenanceRecordSz);

                //增加返回model
                list.add(maintenanceRecordSz);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("更新电梯维保记录成功");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("更新电梯维保记录出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/updateMaintenanceRecordByMtInfo")
    public String updateMaintenanceRecordByMtInfo(MaintenanceRecordSz maintenanceRecordSz, Model model, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("更新电梯维保记录（记录表） ===========================================>>>>>>>>>>>>>>" + maintenanceRecordSz.getRecordId());
            if (!beanValidator(model, maintenanceRecordSz)) {
                return form(maintenanceRecordSz, model);
            }
            if (StringUtils.isNotEmpty(maintenanceRecordSz.getRecordId())) {
                uploadMtFile(maintenanceRecordSz, request, resultData);

                maintenanceRecordSz.setLastUpdateBy(UserUtils.getUser().getLoginName());
                maintenanceRecordSzService.updateMaintenanceRecordByMtInfo(maintenanceRecordSz);

                //增加返回model
                list.add(maintenanceRecordSz);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("更新电梯维保记录成功");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("更新电梯维保记录出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/deleteMaintenanceRecordInfo")
    public String deleteMaintenanceRecordInfo(MaintenanceRecordSz maintenanceRecordSz, Model model, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        List<MaintenanceRecordSz> list = new ArrayList();
        try {
            System.out.println("删除电梯维保记录 ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, maintenanceRecordSz)) {
                return form(maintenanceRecordSz, model);
            }
            maintenanceRecordSzService.deleteMaintenanceRecordInfo(maintenanceRecordSz);

            resultData.setFormId(maintenanceRecordSz.getRecordId());
            resultData.setCode("SUCC");
            resultData.setMessage("删除电梯维保记录成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("删除电梯维保记录出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:view")
    @RequestMapping(value = {"list", ""})
    public String list(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) {
        // 设置维保人员和维保单位代码过滤条件
        // maintenanceRecordSz.setCreatedBy(UserFilterUtils.getMainStaff());
        maintenanceRecordSz.setDbName(Global.getConfig("jdbc.type"));
        maintenanceRecordSz.setMaintenUnitCode(UserFilterUtils.getMainUnitCode());

        Page<MaintenanceRecordSz> page = maintenanceRecordSzService.findPage(new Page<MaintenanceRecordSz>(request, response), maintenanceRecordSz);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/maintenanceRecordSzList";
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:view")
    @RequestMapping(value = {"detail"})
    public String detail(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<MaintenanceRecordSz> page = maintenanceRecordSzService.findPage(new Page<MaintenanceRecordSz>(request, response), maintenanceRecordSz);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/maintenanceRecordSzDetail";
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:view")
    @RequestMapping(value = "form")
    public String form(MaintenanceRecordSz maintenanceRecordSz, Model model) {
        // 故障状态
        model.addAttribute("allFailureStatus", DictUtils.getDictList("FAILURE_STATUS"));
        String failureStatus = maintenanceRecordSz.getFailurePhenomenon();

        List failureStatusList = new ArrayList();
        if (StringUtils.isNotEmpty(failureStatus)) {
            String[] failureStatusArray = failureStatus.split(",");
            for (int i = 0; i < failureStatusArray.length; i++) {
                failureStatusList.add(failureStatusArray[i]);
            }
        }
        maintenanceRecordSz.setFailureStatusList(failureStatusList);

        model.addAttribute("maintenanceRecordSz", maintenanceRecordSz);
        return "zhuoyue/elmt/maintenanceRecordSzForm";
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:view")
    @RequestMapping(value = "print")
    public void print(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        DataSource dataSource = SpringContextHolder.getBean(DataSource.class);

        String fileName = "report/wbmainreport/wb_zb.jasper";

        ServletOutputStream ouputStream = null;
        InputStream is = null;
        byte[] bytes = null;
        try {
            Dict dict = dictService.findByIDValue(maintenanceRecordSz.getDeviceVariety());
            String deviceType = "1";
            if (dict != null) {
                deviceType = dict.getValue();
            }

            String dirc = request.getSession().getServletContext().getRealPath("/") + fileName.substring(0, fileName.lastIndexOf("/") + 1);
            String imgDirc = request.getSession().getServletContext().getRealPath("report/images/") + "\\";
            Map parameters = new HashMap();
            parameters.put("record_id", new Integer(maintenanceRecordSz.getRecordId()));
            parameters.put("DTTYPE", deviceType);
            parameters.put("SUBREPORT_DIR", dirc);
            parameters.put("IMAGES_DIR", imgDirc);
            is = request.getSession().getServletContext().getResourceAsStream("/" + fileName);
            bytes = JasperRunManager.runReportToPdf(is, parameters, dataSource.getConnection());

            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);

            ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);

            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                ouputStream.close();
            }
        }
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:edit")
    @RequestMapping(value = "save")
    public String save(MaintenanceRecordSz maintenanceRecordSz, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, maintenanceRecordSz)) {
            return form(maintenanceRecordSz, model);
        }
        maintenanceRecordSzService.save(maintenanceRecordSz);
        addMessage(redirectAttributes, "保存电梯维保记录成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceRecordSz/?repage";
    }

    @RequiresPermissions("elmt:maintenanceRecordSz:edit")
    @RequestMapping(value = "delete")
    public String delete(MaintenanceRecordSz maintenanceRecordSz, RedirectAttributes redirectAttributes) {
        maintenanceRecordSzService.delete(maintenanceRecordSz);
        addMessage(redirectAttributes, "删除电梯维保记录成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/maintenanceRecordSz/?repage";
    }


    /**
     * 查询字典表
     *
     * @param maintenanceRecordSz
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/findSysDictList")
    public String findSysDictList(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<Dict>> resultData = new ResultData();
        try {
            System.out.println("查询字典表 ===========================================>>>>>>>>>>>>>>");
            List<Dict> list = maintenanceRecordSzService.findSysDictList(null);
            if (null == list) {
                list = new ArrayList<Dict>();
            }

            List<AdministrativeAreas> xzqyList = service.getAll();
            List<XtSbzl> sbzlList = xtSbzlService.findDeviceTypeAll();

            resultData.setList(list);

            if (null == xzqyList) {
                xzqyList = new ArrayList<AdministrativeAreas>();
            }

            if (null == sbzlList) {
                sbzlList = new ArrayList<XtSbzl>();
            }

            resultData.setXzqyList(xzqyList);
            resultData.setSbzlList(sbzlList);

            resultData.setCode("SUCC");
            resultData.setMessage("");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("字典表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询维保记录项目表
     *
     * @param maintenanceRecordSz
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/findMaintenanceRecordItem")
    public String findMaintenanceRecordItem(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<HashMap>> resultData = new ResultData();
        try {
            System.out.println("查询电梯维保项目表 ===========================================>>>>>>>>>>>>>>");
            HashMap params = new HashMap();
            params.put("dbName", Global.getConfig("jdbc.type"));
            params.put("recordId", maintenanceRecordSz.getRecordId());//维保记录ID

            List<String> mtTypeList = Lists.newArrayList();
            if (StringUtils.isNotEmpty(maintenanceRecordSz.getYearMainType()) && "1".equals(maintenanceRecordSz.getYearMainType())) {
                mtTypeList.add("4");
                mtTypeList.add("3");
                mtTypeList.add("2");
                mtTypeList.add("1");
            } else if (StringUtils.isNotEmpty(maintenanceRecordSz.getHalfyearMainType()) && "1".equals(maintenanceRecordSz.getHalfyearMainType())) {
                mtTypeList.add("3");
                mtTypeList.add("2");
                mtTypeList.add("1");
            } else if (StringUtils.isNotEmpty(maintenanceRecordSz.getQuarterMainType()) && "1".equals(maintenanceRecordSz.getQuarterMainType())) {
                mtTypeList.add("2");
                mtTypeList.add("1");
            } else if (StringUtils.isNotEmpty(maintenanceRecordSz.getHalfmonthMainType()) && "1".equals(maintenanceRecordSz.getHalfmonthMainType())) {
                mtTypeList.add("1");
            } else {
                mtTypeList.add("1");
            }

            Dict dict = dictService.findByIDValue(maintenanceRecordSz.getDeviceVariety());
            String deviceType = "1";
            if (dict != null) {
                deviceType = dict.getValue();
            }

            params.put("mtTypeList", mtTypeList);//维保类型：例行保养，季度，半年，年度维护
            params.put("mtDeviceType", deviceType);//编码库已维护设备品种:3110，3112,3210到设备类型：1，电梯；2，液压梯；3，杂物梯；4，扶梯的转换关系
            List<HashMap> list = maintenanceRecordSzService.findMaintenanceRecordItem(params);
            if (null == list) {
                list = new ArrayList<HashMap>();
            }
            resultData.setList(list);
            resultData.setCode("SUCC");
            resultData.setMessage("");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯维保项目表查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/saveMaintenanceRecordItem")
    @ResponseBody
    public String saveMaintenanceRecordItem(@RequestBody String body, Model model, HttpServletResponse response) {
        ResultData<List<MaintenanceRecordSz>> resultData = new ResultData();
        ArrayList<MaintenanceRecordItem> array = new ArrayList();
        try {
            System.out.println("保存维保记录项目表数据 ===========================================>>>>>>>>>>>>>>");
            System.out.println("=========================================== RequestBody ===========================================");
            System.out.println("body::::::::::::::::" + body);
            System.out.println("=========================================== RequestBody ===========================================");
            String recordId = null;
            if (body != null && !body.equals("")) {
                JSONObject object = JSONObject.fromObject(body);
                recordId = (String) object.get("recordId");

                JSONArray jsnoArray = (JSONArray) object.get("items");
                for (Iterator iter = jsnoArray.iterator(); iter.hasNext(); ) {
                    JSONObject jsonObject = (JSONObject) iter.next();
                    MaintenanceRecordItem item = (MaintenanceRecordItem) JSONObject.toBean(jsonObject, MaintenanceRecordItem.class);
                    array.add(item);
                }

                if (StringUtils.isNotEmpty(recordId)) {
                    maintenanceRecordSzService.saveWbMaintenanceItemList(recordId, array);
                }
            }
            resultData.setCode("SUCC");
            resultData.setMessage("保存维保记录项目表数据成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("保存维保记录项目表数据出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    private void uploadMtFile(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, ResultData<List<MaintenanceRecordSz>> resultData) {
        // 上传文件
        String wbdwdm = UserUtils.getUser().getCompany().getCode();
        String userid = UserUtils.getUser().getLoginName();
        if (request instanceof MultipartHttpServletRequest) {
            MultipartFile safety_officer_photo = ((MultipartHttpServletRequest) request).getFile("safety_officer_photo");
            if (safety_officer_photo != null && !safety_officer_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + wbdwdm + "/" + userid + "/" + "mtsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = safety_officer_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    safety_officer_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    maintenanceRecordSz.setSafetyOfficerPhoto(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("管理人员签名上传失败");
                    e.printStackTrace();
                    maintenanceRecordSz.setSafetyOfficerPhoto("");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("管理人员签名上传失败");
            }

            MultipartFile maintenance_staff1_photo = ((MultipartHttpServletRequest) request).getFile("maintenance_staff1_photo");
            if (maintenance_staff1_photo != null && !maintenance_staff1_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + wbdwdm + "/" + userid + "/" + "mtsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = maintenance_staff1_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    maintenance_staff1_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    maintenanceRecordSz.setMaintenanceStaff1Photo(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保人员1签名上传失败");
                    e.printStackTrace();
                    maintenanceRecordSz.setMaintenanceStaff1Photo("");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保人员1签名上传失败");
            }

            MultipartFile maintenance_staff2_photo = ((MultipartHttpServletRequest) request).getFile("maintenance_staff2_photo");
            if (maintenance_staff2_photo != null && !maintenance_staff2_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + wbdwdm + "/" + userid + "/" + "mtsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = maintenance_staff2_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    maintenance_staff2_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    maintenanceRecordSz.setMaintenanceStaff2Photo(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保人员2签名上传失败");
                    e.printStackTrace();
                    maintenanceRecordSz.setMaintenanceStaff2Photo("");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保人员2签名上传失败");
            }

            MultipartFile main_record_pic1 = ((MultipartHttpServletRequest) request).getFile("main_record_pic1");
            if (main_record_pic1 != null && !main_record_pic1.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + wbdwdm + "/" + userid + "/" + "mtpic/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = main_record_pic1.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    main_record_pic1.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    maintenanceRecordSz.setMainRecordPic1(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保图片1上传失败");
                    e.printStackTrace();
                    maintenanceRecordSz.setMainRecordPic1("");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保图片1上传失败");
            }

            MultipartFile main_record_pic2 = ((MultipartHttpServletRequest) request).getFile("main_record_pic2");
            if (main_record_pic2 != null && !main_record_pic2.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + wbdwdm + "/" + userid + "/" + "mtpic/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = main_record_pic2.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    main_record_pic2.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    maintenanceRecordSz.setMainRecordPic2(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保图片2上传失败");
                    e.printStackTrace();
                    maintenanceRecordSz.setMainRecordPic2("");
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保图片2上传失败");
            }
        }
    }
}